<template>
    <div class="bac-container-none-padding">
        <div class="bac-container-title">头像修改</div>
        <el-form class="upload-head-form" :inline="true" size="small">
            <el-form-item>
                <el-avatar :size="160" :src="userInfo.headUrl" ></el-avatar>
            </el-form-item>
            <el-form-item style="padding-top:45px;margin-left: 20px ">
                <el-upload action="/" :http-request="uploadImage" :show-file-list="false">
                    <el-button type="primary" size="small">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-form-item>
        </el-form>

    </div>
</template>
<script>
    import common from '@/api/common';
    import commonUtil from "@/utils/commonUtil";

    export default {
        data: function () {
            return {
                uploadUrl: this.$baseURL + "/user/details/updateHeadImage",
                userInfo: {}
            }
        },
        methods: {
            getUserInfo() {
                common.getUserInfo().then((res) => {
                    this.userInfo = res;
                })
            },
            uploadImage(param) {
                let fileObj = param.file;
                const isJPG = fileObj.type === "image/jpeg";
                const isPng = fileObj.type === "image/png";
                const isLt2M = fileObj.size / 1024 < 500;

                if (!isJPG && !isPng) {
                    this.$notify({offset: 60, title: '错误', message: '上传图片只能是jpg/png 格式!', type: 'error'});
                    return;
                }
                if (!isLt2M) {
                    this.$notify({offset: 60, title: '错误', message: '上传图片大小不能超过500kb!', type: 'error'});
                    return;
                }

                // FormData 对象
                var form = new FormData();
                // 文件对象
                form.append("file", fileObj);
                this.$post(this.uploadUrl, form).then((res) => {
                    this.userInfo.headUrl = commonUtil.setUrl(res.data);
                    sessionStorage.removeItem("userInfo");
                    this.$notify({offset: 60, title: '成功', message: '头像上传成功!', type: 'success'});
                })

            }
        },
        mounted() {
            this.getUserInfo();
        }
    }
</script>

<style>
</style>